/*
 * //Author: Karthic Kumar Sekar [A0092622]
 */

package sg.edu.nus.iss.team4ft.service;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.util.*;

import sg.edu.nus.iss.team4ft.exception.InvalidOperationException;
import sg.edu.nus.iss.team4ft.util.AppConstant;
import sg.edu.nus.iss.team4ft.util.IOService;

public class VoicePlan extends Plan  implements UsageChargable, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Long telephoneNumber = 60061001L;
	
	protected VoicePlan(VoicePlan voicePlan) {
		super((Plan)voicePlan);
		this.telephoneNumber = voicePlan.telephoneNumber;
	}
	
	public VoicePlan(Date startDate, PlanCode planCode) throws InvalidOperationException, IOException, ClassNotFoundException{
		super(startDate, planCode);
		setTelephoneNumber(getNewPhoneNumber());
		
		//Fill the feature list with default features.
		subscripeNewFeature(new CallService(startDate, FeatureCode.LocalCall, this));
	}
	//Calculate monthly subcription charge for the plan based only if the plan is active for the given month
	@Override
	public Double getSubscriptionCharge(Date forMonth) throws CloneNotSupportedException {
		double subCharge = 0.0;
		for (Feature f : getFeatures()) {
			subCharge += f.getSubscriptionCharge(forMonth);
		}
		setSubscriptionCharge(subCharge);
		return subCharge;
	}
	
	private void setTelephoneNumber(Long telephoneNumber){		
		this.telephoneNumber = telephoneNumber;
	}

	public Long getTelephoneNumber() {
		return telephoneNumber;
	}
	
	public String getTelephoneNumberInString(){
		return "+65-" + telephoneNumber.toString();
	}

	//Calculate monthly usage charge for the plan based on all the active features
	@Override
	public Double calculateMonthlyUsage(Date forDate)
			throws NullPointerException, IOException, ParseException, CloneNotSupportedException {
		double totalAmount = 0.0;
		for (Feature cs : this.features) {
			if(cs instanceof UsageChargable){
				cs.setPlan(this);
				totalAmount += ((UsageChargable)cs).calculateMonthlyUsage(forDate);
			}
				
		}
		return totalAmount;
	}
	
	public long getNewPhoneNumber() throws IOException, ClassNotFoundException{
		Object o = IOService.readObjFromFile(AppConstant.FILE_TEL_NUM);
		Long numberLong = 60061001L;
		
		if(o != null)
			if(o instanceof Long)
				numberLong = (Long) o;		

		IOService.saveObjToFile(++numberLong, AppConstant.FILE_TEL_NUM);
		return numberLong;
	}	
	
	@Override
	public String toString() {
		String s = super.toString();
		s += "  " + this.telephoneNumber.toString();
		return s;
	}
	
	@Override
	public Plan clone() throws CloneNotSupportedException{
		VoicePlan v = new VoicePlan(this);
		return v;
	}
}
